/**文件目录处理工具 */
import MFile from "./utils/m-file";
/**网络处理工具 */
import MHttp from "./utils/m-http";
/** 进度显示工具 */
import MSpinner from "./utils/m-spinner";

/**业务类型定义 */
import { IGlobal, ISwagger } from "./m-types";
/**命令处理器业务 */
import MCmder from "./services/m-cmder";
/**swagger解析器业务 */
import MParser from "./services/m-parser";
/**文件书写器业务 */
import MWriter from "./services/m-writer";

/**主流程处理 */
export default class MMain {
  /**命令参数 */
  private static parm = {} as IGlobal;
  /**解析Npm命令参数 */
  public static async getParm() {
    MSpinner.start("正在分析命令参数...");
    const parm = await MCmder.getParm();
    Object.assign(MMain.parm, parm);
    MSpinner.success("分析命令参数完成...");
    return MMain;
  }
  /**加载Swagger配置 */
  public static async loadJson() {
    const { swgFile, swgUrl, swgJson } = MMain.parm;
    const { offline, authUser, authPass } = MMain.parm;
    const baseAuth = { user: authUser, pass: authPass };
    let swg = {} as ISwagger;
    MSpinner.start("正在加载swagger数据...");
    if (offline) {
      const res = await MFile.readFile(swgFile);
      swg = JSON.parse(res);
    } else {
      const res = await MHttp.get(swgUrl, null, { baseAuth });
      swg = res.data;
    }
    Object.assign(swgJson, swg);
    MSpinner.success("加载swagger数据完成...");
    return MMain;
  }
  /**解析Swagger数据成格式化数据 */
  public static async parseSwg() {
    const parm = MMain.parm;
    MSpinner.start("正在解析swagger数据...");
    const result = new MParser(parm).parse();
    parm.result = result;
    MSpinner.success("解析swagger数据完成...");
    return MMain;
  }
  /**把格式化数据写成文件 */
  public static async writeFiles() {
    const parm = MMain.parm;
    MSpinner.start("正在书写接口模型文件...");
    await MWriter.write(parm);
    MSpinner.success("书写接口模型文件完成...");
    return MMain;
  }
  /**任务处理成功 */
  public static async success() {
    const { apiPath } = MMain.parm;
    MSpinner.success(`Api发布成功！请查看目录：${apiPath}`);
  }
  /**任务处理失败 */
  public static async fail(err: any) {
    const msg = MMain.getError(err);
    MSpinner.fail(msg);
  }
  /**输出日志 */
  public static async console() {
    console.log(MMain.parm);
    return MMain;
  }

  /**获取异常信息 */
  private static getError(err: any) {
    const isDate = err instanceof Date;
    const isArr = err instanceof Array;
    const isObj = Object.prototype.toString.call(err) == "[object Object]";
    if (isDate) return new Date(err).toString();
    if (isArr) return err[0] || "";
    if (isObj) return err.message || `${err}`;
    return `${err}`;
  }
}
